package snsdbook.engine;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import util.Util;

public class ServerEngine {
  
  public ServerEngine(String port, int request_handlers, long delay) {
    assert request_handlers > 0;
    assert port != null;
    
    BlockingQueue<Socket> sockets = new LinkedBlockingQueue<Socket>();
    
    Util.Log("Creating request handlers");
    // Create pool of request handlers
    for (int i = 0; i < request_handlers; ++i) {
      new Thread(new RequestHandler(sockets)).start();
    }
    

    // Perform socket bindings
    ServerSocket server = null;
    try {
      Util.Log("Starting server at port " + port);
      server = new ServerSocket(Integer.valueOf(port));
      Util.Log("Server started");
      while (true) {
        sockets.add(server.accept());
      }
    } catch (IOException e) {
      Util.Fatal(e);
    }
    
  }
  
}
